package com.offcn.webui.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.dycommon.response.AppResponse;
import com.offcn.webui.service.ProjectServiceFeign;
import com.offcn.webui.service.UserServiceFeign;
import com.offcn.webui.vo.resp.ProjectVo;
import com.offcn.webui.vo.resp.UserRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: wzy
 * @Date: 2021/01/30/17:12
 * @Description:
 */
@Controller
public class DispathcherController {

    @Autowired
    private UserServiceFeign userServiceFeign;
    @Autowired
    private ProjectServiceFeign projectServiceFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/doLogin")
    public String doLogin(String loginacct, String password, HttpSession session) {
        //调用远程服务
        AppResponse<UserRespVo> appResponse = userServiceFeign.login(loginacct, password);
        //获取响应码
        UserRespVo userRespVo = appResponse.getData();
        if (userRespVo == null) {
            // 账号不存在 ，登录
            return "redirect:/login.html";
        }
        //用户存在,登录成功，把用户信息存储到session
        session.setAttribute("sessionMember", userRespVo);
        //从session获取前缀
        String preUrl = (String) session.getAttribute("preUrl");
        //如果前缀不存在，跳转到默认首页
        if (StringUtils.isEmpty(preUrl)) {
            return "redirect:/";
        }
        //如果存在
        return "redirect:/" + preUrl;

    }

    @RequestMapping("/")
    public String toIndex(Model model) {
        //从redis中读取项目集合
        String data = redisTemplate.opsForValue().get("projectStr");
        List<ProjectVo> projectVoList = JSON.parseArray(data, ProjectVo.class);
        if (CollectionUtils.isEmpty(projectVoList)) {
            AppResponse<List<ProjectVo>> all = projectServiceFeign.findAll();
            projectVoList = all.getData();
            redisTemplate.opsForValue().set("projectStr", JSON.toJSONString(projectVoList), 1, TimeUnit.HOURS);
        }
        model.addAttribute("projectList", projectVoList);
        return "index";
    }

}
